using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;
using Work.API.Applications.Write.Commands;
using Work.API.Dtos;

namespace WinFormsApp1
{
    /// <summary>
    /// 开药表单
    /// </summary>
    public partial class PrescriptionForm : Form
    {
        private const string ApiBaseUrl = "http://localhost:5044";
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private readonly AppointmentListDto _appointment;
        private List<PrescriptionItemDto> _prescriptionItems;
        private int? _recordId;

        public PrescriptionForm(AppointmentListDto appointment)
        {
            InitializeComponent();
            _httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
            _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            _appointment = appointment;
            _prescriptionItems = new List<PrescriptionItemDto>();
            
            LoadPatientInfo();
            LoadExistingPrescriptionItems();
        }

        private void LoadPatientInfo()
        {
            lblPatientName.Text = $"患者：{_appointment.PatientName}";
            lblRegistrationNum.Text = $"挂单号：{_appointment.RegistrationNum}";
            lblDepartment.Text = $"科室：{_appointment.Department}";
        }

        private async void LoadExistingPrescriptionItems()
        {
            try
            {
                // 只加载未支付的药品
                var response = await _httpClient.GetAsync(
                    $"api/Prescription/GetByAppointment?appointmentId={_appointment.AppintmentId}&unpaidOnly=true");
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<PrescriptionItemDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == 100 && apiResult.Data != null)
                {
                    // 只加载未支付的药品，已支付的不显示
                    _prescriptionItems = apiResult.Data.Where(x => x.PaymentStatus == "未支付").ToList();
                    RefreshDataGridView();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载处方明细失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void RefreshDataGridView()
        {
            dgvPrescriptionItems.DataSource = null;
            
            // 只显示未支付的药品，过滤掉已支付的
            var unpaidItems = _prescriptionItems.Where(item => 
                item.PrescriptionItemId == 0 || item.PaymentStatus == "未支付").ToList();
            
            // 使用索引作为ID，因为新添加的项还没有PrescriptionItemId
            var data = unpaidItems.Select((item, index) => new
            {
                药品名称 = item.MedicineName,
                单价 = item.UnitPrice,
                数量 = item.Quantity,
                总金额 = item.TotalAmount,
                支付状态 = item.PaymentStatus ?? "未支付",
                索引 = index,
                ItemId = item.PrescriptionItemId
            }).ToList();
            
            dgvPrescriptionItems.DataSource = data;

            // 配置列显示
            if (dgvPrescriptionItems.Columns.Contains("索引"))
                dgvPrescriptionItems.Columns["索引"].Visible = false;
            if (dgvPrescriptionItems.Columns.Contains("ItemId"))
                dgvPrescriptionItems.Columns["ItemId"].Visible = false;
            if (dgvPrescriptionItems.Columns.Contains("支付状态"))
                dgvPrescriptionItems.Columns["支付状态"].Visible = false;

            CalculateTotal();
        }

        private void CalculateTotal()
        {
            // 只计算未支付药品的总金额
            var total = _prescriptionItems
                .Where(x => x.PrescriptionItemId == 0 || x.PaymentStatus == "未支付")
                .Sum(x => x.TotalAmount);
            lblTotalAmount.Text = $"总金额：{total:F2} 元";
        }

        private void btnAddMedicine_Click(object? sender, EventArgs e)
        {
            // 打开添加药品对话框
            using (var addForm = new AddMedicineDialog())
            {
                if (addForm.ShowDialog(this) == DialogResult.OK)
                {
            var item = new PrescriptionItemDto
            {
                PrescriptionItemId = 0, // 新添加的项ID为0
                MedicineName = addForm.MedicineName,
                UnitPrice = addForm.UnitPrice,
                Quantity = addForm.Quantity,
                TotalAmount = addForm.UnitPrice * addForm.Quantity,
                PaymentStatus = "未支付"
            };

            _prescriptionItems.Add(item);
            RefreshDataGridView();
                }
            }
        }

        private async void btnDelete_Click(object? sender, EventArgs e)
        {
            if (dgvPrescriptionItems.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要删除的药品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedRow = dgvPrescriptionItems.SelectedRows[0];
            int selectedIndex;
            
            // 从DataGridView获取索引
            if (selectedRow.Cells["索引"].Value != null && int.TryParse(selectedRow.Cells["索引"].Value.ToString(), out selectedIndex))
            {
                // 使用获取到的索引
            }
            else
            {
                selectedIndex = selectedRow.Index;
            }
            
            // 获取未支付药品列表
            var unpaidItems = _prescriptionItems.Where(item => 
                item.PrescriptionItemId == 0 || item.PaymentStatus == "未支付").ToList();
            
            if (selectedIndex >= 0 && selectedIndex < unpaidItems.Count)
            {
                var item = unpaidItems[selectedIndex];
                
                // 如果是已保存的记录且已支付，不能删除（理论上不应该出现在列表中）
                if (item.PrescriptionItemId > 0 && item.PaymentStatus == "已支付")
                {
                    MessageBox.Show("已支付的药品不能删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (MessageBox.Show("确定要删除这条药品吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    // 如果是已保存的未支付药品，需要调用删除API
                    if (item.PrescriptionItemId > 0)
                    {
                        await DeletePrescriptionItemAsync(item.PrescriptionItemId);
                    }
                    
                    // 从列表中移除
                    _prescriptionItems.Remove(item);
                    RefreshDataGridView();
                }
            }
        }

        private async void btnSave_Click(object? sender, EventArgs e)
        {
            if (_prescriptionItems.Count == 0)
            {
                MessageBox.Show("请至少添加一种药品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            btnSave.Enabled = false;

            try
            {
                // 获取病历ID（如果存在）
                var recordResponse = await _httpClient.GetAsync(
                    $"api/MedicalRecord/GetByAppointmentId?appointmentId={_appointment.AppintmentId}");
                var recordJson = await recordResponse.Content.ReadAsStringAsync();
                var recordResult = JsonSerializer.Deserialize<ApiResult<MedicalRecordDto?>>(recordJson, _jsonOptions);
                _recordId = recordResult?.Data?.RecordId;

                // 只保存新添加的未支付药品（PrescriptionItemId == 0 表示新添加的）
                var newItems = _prescriptionItems
                    .Where(item => item.PrescriptionItemId == 0 && (item.PaymentStatus == "未支付" || string.IsNullOrEmpty(item.PaymentStatus)))
                    .ToList();
                
                if (newItems.Count == 0)
                {
                    MessageBox.Show("没有新添加的药品需要保存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnSave.Enabled = true;
                    return;
                }

                // 只保存新添加的药品（已保存的药品保持不变）
                var command = new CreatePrescriptionItemsCommand
                {
                    AppointmentId = _appointment.AppintmentId,
                    RecordId = _recordId,
                    PatientId = _appointment.PatientId,
                    RegistrationNum = _appointment.RegistrationNum,
                    CreateBy = _appointment.DoctorName,
                    Items = newItems.Select(item => new PrescriptionItemInfo
                    {
                        MedicineName = item.MedicineName,
                        UnitPrice = item.UnitPrice,
                        Quantity = item.Quantity
                    }).ToList()
                };

                var json = JsonSerializer.Serialize(command);
                using var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync("api/Prescription/CreateBatch", content);
                response.EnsureSuccessStatusCode();
                var respJson = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<int>>(respJson, _jsonOptions);

                if (apiResult != null && apiResult.Code == 100)
                {
                    MessageBox.Show("处方保存成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "保存失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnSave.Enabled = true;
            }
        }

        private void btnCancel_Click(object? sender, EventArgs e)
        {
            this.Close();
        }

        private async System.Threading.Tasks.Task DeletePrescriptionItemAsync(int prescriptionItemId)
        {
            try
            {
                var deleteCommand = new DeletePrescriptionItemCommand
                {
                    PrescriptionItemId = prescriptionItemId
                };
                var json = JsonSerializer.Serialize(deleteCommand);
                using var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync("api/Prescription/Delete", content);
                response.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                // 记录错误但不阻止继续执行
                System.Diagnostics.Debug.WriteLine($"删除处方明细失败：{ex.Message}");
            }
        }

        // 内部类：添加药品对话框
        private class AddMedicineDialog : Form
        {
            private TextBox txtMedicineName;
            private TextBox txtUnitPrice;
            private TextBox txtQuantity;
            private Button btnOK;
            private Button btnCancel;

            public string MedicineName => txtMedicineName.Text;
            public decimal UnitPrice => decimal.TryParse(txtUnitPrice.Text, out var price) ? price : 0;
            public int Quantity => int.TryParse(txtQuantity.Text, out var qty) ? qty : 0;

            public AddMedicineDialog()
            {
                this.Text = "添加药品";
                this.Size = new System.Drawing.Size(350, 200);
                this.StartPosition = FormStartPosition.CenterParent;
                this.FormBorderStyle = FormBorderStyle.FixedDialog;
                this.MaximizeBox = false;
                this.MinimizeBox = false;

                var lblName = new Label { Text = "药品名称：", Location = new System.Drawing.Point(20, 20), Width = 80 };
                txtMedicineName = new TextBox { Location = new System.Drawing.Point(100, 18), Width = 200 };

                var lblPrice = new Label { Text = "单价：", Location = new System.Drawing.Point(20, 50), Width = 80 };
                txtUnitPrice = new TextBox { Location = new System.Drawing.Point(100, 48), Width = 200 };

                var lblQty = new Label { Text = "数量：", Location = new System.Drawing.Point(20, 80), Width = 80 };
                txtQuantity = new TextBox { Location = new System.Drawing.Point(100, 78), Width = 200 };

                btnOK = new Button { Text = "确定", DialogResult = DialogResult.OK, Location = new System.Drawing.Point(140, 120), Width = 75 };
                btnCancel = new Button { Text = "取消", DialogResult = DialogResult.Cancel, Location = new System.Drawing.Point(225, 120), Width = 75 };

                btnOK.Click += (s, e) =>
                {
                    if (string.IsNullOrWhiteSpace(txtMedicineName.Text))
                    {
                        MessageBox.Show("请输入药品名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.DialogResult = DialogResult.None;
                        return;
                    }
                    if (UnitPrice <= 0)
                    {
                        MessageBox.Show("请输入有效的单价", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.DialogResult = DialogResult.None;
                        return;
                    }
                    if (Quantity <= 0)
                    {
                        MessageBox.Show("请输入有效的数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.DialogResult = DialogResult.None;
                        return;
                    }
                };

                this.Controls.AddRange(new Control[] { lblName, txtMedicineName, lblPrice, txtUnitPrice, lblQty, txtQuantity, btnOK, btnCancel });
            }
        }

        private class ApiResult<T>
        {
            public int Code { get; set; }
            public string? Message { get; set; }
            public T? Data { get; set; }
        }
    }
}

